<?php

class Controller_Admin_Settings extends Controller_Admin_Template
{
	private $db;

	public function before()
	{
		parent::before();
		$this->db = Database::instance();
		$this->template->title = 'Website settings';
		$this->template->content = '';
//        $this->addScript('/scripts/jquery/12/jquery-ui.min.js');
//        $this->addScript('/scripts/jquery/12/jquery.js');
        $this->addScript('/scripts/eva.js');
        $this->addStyle('/styles/eva.css');
	}

	public function actionIndex()
	{
		$form = new Form('item', '<b>Edit settings</b>');
		$form->labelWidth = '220px';
		$user = Auth::getInstance()->getIdentity();
		foreach (Database::instance()->query('SELECT * FROM `settings`')->fetchAll() as $setting) {
			if ($setting['root'] && $user['role'] != 'root') {
				continue;
			}
			switch ($setting['type']) {
				case 'text':
					$form->text($setting['key'], $setting['name'])->attribute('size', 40);
					break;
				case 'checkbox':
					$form->checkbox($setting['key'], '', $setting['name'])->attribute('size', 40);
					break;
				case 'select':
					if ($setting['options']) {
						$options = array();
						foreach (json_decode($setting['options']) as $k => $v) {
							$options[$k] = $v;
						}
					}
					$form->select($setting['key'], $options, $setting['name']);
					break;
			}
			if ($setting['rules']) {
				foreach (json_decode($setting['rules']) as $rule => $param) {
					$form->elements[$setting['key']]->rule($rule, $param);
				}
			}
		}
		$form->submit('submit', 'Save');
		$form->loadValues($this->settings);

		$this->template->content = '';

		if ('POST' == Request::$method) {
			if ($form->validate()) {
				$values = $form->getValues();
				foreach ($values as $k => $v) {
					$this->db->query('UPDATE `settings` SET `value` = ? WHERE `key` = ?', array($v, $k));
				}
				$this->template->content = '<p class="box-info feedback-message">' . Text::CHANGES_SAVED . '</p>';
			}
		}
		$this->template->content .= $form;
		$identity = Auth::getInstance()->getIdentity();
		if ($identity['role'] == 'root') {
			$this->template->content .= new View('admin/settings-options', array('options' => Database::instance()->query('SELECT * FROM `settings`')->fetchAll()));
		}
	}

	public function actionAdd()
	{
		$this->actionEdit();
	}

	public function actionEdit($key = null)
	{
		$identity = Auth::getInstance()->getIdentity();
		if ($identity['role'] != 'root') {
			throw new ForbiddenException('You are not authorized for this action');
		}
		if (!$key) {
			$this->template->title = 'Add new settings option';
		} else {
			$this->template->title = 'Edit settings option';
			if (!($option = Database::instance()->query('SELECT * FROM `settings` WHERE `key` = ?', $key)->fetch())) {
				throw new NotFoundException('Key not found');
			}
		}
		$form = new Form('newOption');
		$form->text('name', 'Label')->attribute('size', 40);
		$form->text('key', 'Key')->callback('checkUnique', array('key' => $key))->attribute('size', 40);
		$form->checkbox('root', '', 'Visible to root only')->attribute('size', 40);
		function checkUnique($field, $args)
		{
			
			extract($args);

			if(!preg_match('/^[a-zA-Z0-9.-]+$/us', $field->value)) {
				$field->error('Only letters, numbers, "-" and "." are allowed');
			}

			if (isset($key)) {
				if (Database::instance()->query('SELECT 1 FROM `settings` WHERE `key` = ? AND `key` != ?', array($field->value, $key))->fetch()) {
					$field->error(Text::DUPLICATE_KEY);
				}
			} else {
				if (Database::instance()->query('SELECT 1 FROM `settings` WHERE `key` = ?', $field->value)->fetch()) {
					$field->error(Text::DUPLICATE_KEY);
				}
			}
		}
		$form->select('type', array(
			'text' => 'Text',
			'select' => 'Text',
			'checkbox' => 'Checkbox',
		), 'Control type');
		$form->textarea('rules', 'Rules (JSON)')->attribute('cols', 80)->attribute('rows', 10);
		$form->textarea('options', 'Options (JSON)')->attribute('cols', 80)->attribute('rows', 10);
		$form->submit('submit', 'Save');
		$this->template->content = $form;
		if ($key) {
			$form->loadValues($option);
		}
		if ('POST' == Request::$method) {
			if ($form->validate()) {
				if ($key) {
					$values = $form->getModified();
					Model_Table::instance('settings')->keys['string'] = 'key';
					Model_Table::instance('settings')->update($values, $key);
				} else {
					$values = $form->getValues();
					Model_Table::instance('settings')->insert($values);
				}
				$this->response->redirect(Request::$controller);
			}
		}
	}

	public function actionRemove($key)
	{
		$identity = Auth::getInstance()->getIdentity();
		if ($identity['role'] != 'root') {
			throw new ForbiddenException('You are not authorized for this action');
		}
		if (!$key) {
			$this->template->title = 'Add new settings option';
		} else {
			$this->template->title = 'Edit settings option';
			if (!($option = Database::instance()->query('SELECT * FROM `settings` WHERE `key` = ?', $key)->fetch())) {
				throw new NotFoundException('Key noty found');
			}
		}
		Model_Table::instance('settings')->keys['string'] = 'key';
		Model_Table::instance('settings')->delete($key);
		$this->response->redirect(Request::$controller);
	}
}
?>